#include "triangle.h"
#include <QSGFlatColorMaterial>
#include <QSGGeometry>
#include <QSGGeometryNode>
#include <QSGMaterial>

Triangle::Triangle(QQuickItem* parent)
    : Super(parent)
{
    setFlag(Super::ItemHasContents);
}

Triangle::~Triangle() { }

static QColor fColor(qreal r, qreal g, qreal b, qreal a = 1.0)
{
    return QColor((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255));
}
QSGNode* Triangle::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData* data)
{
    (void)data;

    QSGGeometry*     geo = nullptr;
    QSGGeometryNode* node = nullptr;
    const int        cVertexCount = 3;
    if (!oldNode)
    {
        node = new QSGGeometryNode;
        geo = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), cVertexCount);
        geo->setLineWidth(1);
        geo->setDrawingMode(QSGGeometry::DrawTriangles);

        node->setGeometry(geo);
        node->setFlag(QSGNode::OwnsGeometry);

        auto material = new QSGFlatColorMaterial;
        auto color = fColor(1.0f, 0.5f, 0.2f, 1.0f);
        material->setColor(color);

        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);
    }
    else
    {
        node = static_cast<QSGGeometryNode*>(oldNode);
        geo = node->geometry();
        geo->allocate(cVertexCount);
    }
    auto vertices = geo->vertexDataAsPoint2D();
    int  w = width();
    int  h = height();
    vertices[0].set(0.5 * w, 0.1 * h);
    vertices[1].set(0.9 * w, 0.9 * h);
    vertices[2].set(0.1 * w, 0.9 * h);
    node->markDirty(QSGNode::DirtyGeometry);
    return node;
}
